<?php
/**
 * Created by PhpStorm.
 * User: yyq
 * Date: 2018/9/17
 * Time: 21:10
 */

namespace Web\Controller;


use Advertisement\Model\BannerImageModel;
use Advertisement\Model\BannerModel;
use Common\Model\AppConfigModel;
use Common\Model\AttrDetailModel;
use Common\Model\CartModel;
use Common\Model\CategoryModel;
use Common\Model\ContactModel;
use Common\Model\MemberModel;
use Common\Model\OrderModel;
use Common\Model\ProAttrModel;
use Common\Model\ProductModel;
use Common\Model\ProOptionModel;
use Common\Model\RefundModel;
use System\Model\DocumentsModel;

class IndexController extends WebbaseController
{
    private $app_config_model;
    private $member_model;
    private $member_info;
    private $product_model;
    private $pro_attr_model;
    private $attr_detail_model;
    private $pro_option_model;
    private $cart_model;
    private $documents_model;
    private $contact_model;
    private $order_model;
    private $refund_model;
    private $banner_model;
    private $banner_image_model;
    private $category_model;

    public function __construct()
    {
        parent::__construct();
        $this->app_config_model = new AppConfigModel();
        $this->member_model     = new MemberModel();
        $this->product_model    = new ProductModel();
        $this->pro_attr_model   = new ProAttrModel();
        $this->attr_detail_model= new AttrDetailModel();
        $this->pro_option_model = new ProOptionModel();
        $this->cart_model       = new CartModel();
        $this->documents_model  = new DocumentsModel();
        $this->contact_model    = new ContactModel();
        $this->order_model      = new OrderModel();
        $this->refund_model     = new RefundModel();
        $this->banner_image_model   = new BannerImageModel();
        $this->banner_model     = new BannerModel();
        $this->category_model   = new CategoryModel();
        $this->member_info      = session('member_info');
    }

    public function header() {

        $this->display();
    }
    public function footer() {

        $this->display();
    }

    public function left() {

        $this->display();
    }


    public function index() {
        $home_link = $this->app_config_model->getOptionValue('home_link');
        $this->assign('home_link', $home_link);


        $this->display();
    }

    public function home() {
        $cate_id = I('get.cate_id');
        $_SESSION['cate_id']    = $cate_id;
        //banner图
        $banner = $this->banner_model->getBanner(BannerModel::APP_STORE);

        $list = $this->product_model->getList(['hot' => 'yes', 'if_show' => ProductModel::SHOW_YES, 'status' => 'up'], '0, 11');

        $para['banner'] = $banner;
        $para['list'] = $list;

        $this->assign($para);
        $this->display();
    }

    public function login() {
        if($this->member_info['mid']) {
            $this->checktoken($this->member_info['mid'], $this->member_info['token']);
        }

        $this->assign($this->member_info);
        $this->display();
    }

    /**
     * 登录操作
     */
    public function doLogin() {
        if (!IS_POST)
            exit($this->returnApiError(WeixinbaseController::INVALID_INTERFACE));

        $userAccount = I("post.username");
        $userPassword = I("post.password");
//        dump($_POST);exit;

        $where = [
            'username' => $userAccount,
            'password' => sp_password($userPassword),
        ];
        $field = 'id as mid, username,header, nickname, phone, birthday, hobby, email, sex';
        $members = $this->member_model
            ->field($field)
            ->where($where)
            ->find();
//        dump($members);die;
        if (!$members) {
            $where = [
                'phone'     => $userAccount,
                'password'  => sp_password($userPassword),
            ];
            $field = 'id as mid, username,header, nickname, phone, birthday, hobby, email, sex';
            $members = $this->member_model
                ->field($field)
                ->where($where)
                ->find();
            if(!$members) {
                exit($this->returnApiError(WebbaseController::FATAL_ERROR, '帐号或者密码错误'));

            }
        }

        $members['header'] = setUrl($members['header']);

        $token = $this->createtoken();
        $token_time_out = time() + 3600 * 24 * 7;
        $save_result = $this->member_model->where(['id' => $members['mid']])->save(
            [
                'token'          => $token,
                'token_time_out' => $token_time_out,
                'ip'             => get_client_ip(),
            ]);

        $members['token'] = $token;

        if ($save_result === false) {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '登录错误'));
        }

        $_SESSION['member_info'] = $members;
        exit($this->returnApiSuccess());
    }

    public function getpassword() {

        $this->display();
    }



    /**
     * 退出登录
     */
    public function userLoginOut()
    {
//        if (!IS_POST) exit($this->returnApiError(ApibaseController::INVALID_INTERFACE));

        $mid = $this->member_info['mid'];
        $this->checkparam([$mid]);

        $result = $this->member_model
            ->where(['id' => $mid])
            ->save([
                'token'          => '',
                'token_time_out' => '',
            ]);
        if ($result === false) exit($this->returnApiError(ApibaseController::FATAL_ERROR));
        $_SESSION['member_info'] = [];
//        $this->redirect(U('home'));
        exit($this->returnApiSuccess());
    }

    /**
     * 商品详情
     */
    public function show() {
        $pro_id = I('get.pro_id');
        $pro_info = $this->product_model->find($pro_id);
        if(!$pro_info) {
            $this->error('商品不存在');
        }
        if($pro_info['status'] == ProductModel::STATUS_DOWN) {
            $this->error('该商品已下架');
        }
        //商品信息
        $pro_info['cover_photo'] = setUrl($pro_info['cover_photo']);
        $pro_info['smeta'] = setUrl(json_decode($pro_info['cover_photo'], true));
        $this->assign('info', $pro_info);

        //规格属性
        $attr = $this->pro_attr_model
            ->alias('a')
            ->join('left join he_attribute as b on a.attr_id = b.attr_id')
            ->where(['a.pro_id' => $pro_id])
            ->field('a.attr_id, b.attr_name')
            ->select();
        foreach ($attr as $k => $v) {
            $detail = $this->attr_detail_model->where(['pro_id' => $pro_id, 'attr_id' => $v['attr_id']])->field('detail_name, de_id')->select();
            $attr[$k]['detail'] = $detail;
        }

        //价格
        $pro_option = $this->pro_option_model->where(['pro_id' => $pro_id])->select();

        //更多商品
        $list = $this->product_model->getList(['if_show' => ProductModel::SHOW_YES, 'status' => 'up'], '100', 'pro_id desc');

        $para['list']   = $list;
        $para['attr']   = $attr;
        $para['option'] = json_encode($pro_option,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
        $para['count']  = count($attr);

        $this->assign($para);

        $this->display();
    }

    //个人中心
    public function personal() {

        $this->display();
    }

    //联系我们
    public function contact() {
        $para['address'] = $this->documents_model->where(['doc_class' => 'address'])->getField('content');
        $para['begin'] = $this->documents_model->where(['doc_class' => 'begin'])->getField('content');
        $para['participate'] = $this->documents_model->where(['doc_class' => 'participate'])->getField('content');

        $this->assign($para);
        $this->display();
    }

    public function addContact() {
        $contact = I('post.contact');
        if($this->contact_model->add(['mid' => $this->member_info['mid'], 'contact' => $contact, 'create_time' => getTime()])) {
            exit($this->returnApiSuccess());
        } else {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR));
        }
    }

    //关注氦闪
    public function follow() {

        $this->display();
    }

    //选号规则
    public function rules() {
        $para['number_rule'] = $this->documents_model->where(['doc_class' => 'number_rule'])->getField('content');

        $this->assign($para);
        $this->display();
    }

    //品牌故事
    public function story() {
        $home_link = $this->app_config_model->getOptionValue('story');
        $this->assign('story', $home_link);

        $content = $this->documents_model->where(['doc_class' => 'story'])->find();

        $this->assign('content', $content['content']);
        $this->display();
    }

    //购买须知
    public function notice() {
        $para['buy_know'] = $this->documents_model->where(['doc_class' => 'buy_know'])->getField('content');

        $this->assign($para);
        $this->display();
    }

    //常见问题
    public function difficulty() {
        $para['problem'] = $this->documents_model->where(['doc_class' => 'problem'])->getField('content');
        $para['pay'] = $this->documents_model->where(['doc_class' => 'pay'])->getField('content');
        $para['deliver'] = $this->documents_model->where(['doc_class' => 'deliver'])->getField('content');
        $para['sale_service'] = $this->documents_model->where(['doc_class' => 'sale_service'])->getField('content');

        $this->assign($para);
        $this->display();
    }

    //政策
    public function policy() {
        $para['private'] = $this->documents_model->where(['doc_class' => 'private'])->getField('content');
        $para['buy_rule'] = $this->documents_model->where(['doc_class' => 'buy_rule'])->getField('content');

        $this->assign($para);
        $this->display();
    }

    //用户信息
    public function user_info() {
        if(IS_POST) {
            $post = $_POST;
            foreach ($post as $k => $v) {
                if(!$v) {
                    unset($post[$k]);
                }
                if($k == 'password' && $v) {
                    $post[$k] = sp_password($v);
                }
                foreach ($this->member_info as $key => $val) {
                    if($k == $key && $v == $val) {
                        unset($post[$k]);
                    }
                }
            }
//            dump($post);dump($this->member_info);die;
            if($this->member_model->where(['id' => $this->member_info['mid']])->save($post)) {
                $field = 'id as mid, username,header, nickname, phone, birthday, hobby, email, sex';
                $members = $this->member_model
                    ->field($field)
                    ->where(['id' => $this->member_info['mid']])
                    ->find();



                $members['header'] = setUrl($members['header']);

                $_SESSION['member_info'] = $members;
                echo "<script language=JavaScript> location.replace(location.href);</script>";


//                $this->success('保存成功');
            } else {
                echo "<script language=JavaScript> alert('修改信息失败');location.replace(location.href)</script>";


//                $this->error('保存失败');
            }
        } else {
            $this->category_model= new CategoryModel();
            $category = $this->category_model->where(['if_show' => 'yes'])->select();

            $this->assign('category', $category);
            $this->display();
        }
    }

    public function user() {
        $this->order_model->dealOrder();

        $mid = $this->member_info['mid'];
        $order = $this->order_model
            ->alias('a')
            ->where(['mid' => $mid, 'shows' => OrderModel::SHOW_ON, 'a.status' => ['in', [OrderModel::STATUS_WAIT_FOR_PAY, OrderModel::STATUS_PAY_SUCCESS, OrderModel::STATUS_COMPLETE, OrderModel::STATUS_WAIT_COMMENT, OrderModel::STATUS_SEND]]])
            ->join('left join he_order_product as b on a.id = b.order_id')
            ->join('left join he_pro_option as c on b.option_id = c.option_id')
            ->join('left join he_product as d on b.pro_id = d.pro_id')
            ->field('a.id as order_id,a.status, a.order_price,b.quantity,  b.number,b.cover_photo,b.price, b.pro_id, c.option_name, d.product_name, DATE_FORMAT( a.create_time, "%Y-%m-%d") as create_time')
            ->order('a.create_time desc')
            ->select();
        foreach ($order as $k => $v) {
            $order[$k]['status_string'] = $this->order_model->getUserStatusString($v['status']);
        }

        $this->assign('list', $order);
        $this->display();
    }

    public function sureGet() {
        $order_id = I('post.order_id');

        if($this->order_model->where(['id' => $order_id])->save(['status' => OrderModel::STATUS_COMPLETE, 'update_time' => getTime()])) {
            exit($this->returnApiSuccess());
        } else {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '网络错误，请重试'));
        }
    }

    /**
     * 申请退款
     */
    public function refund() {
        $order_id = I('post.order_id');
        $order_info = $this->order_model->find($order_id);
        if($order_info['status'] != OrderModel::STATUS_PAY_SUCCESS) {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '当前订单状态不支持退款'));
        }

        if($this->refund_model->where(['order_id' => $order_id, 'status' => ['in', [RefundModel::STATUS_WAIT, RefundModel::STATUS_ACCEPT]] ])->find()) {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '申请已提交或已处理'));
        }

        $out_refund_no = $this->refund_model->getRefundOrder();

        $data = [
            'order_id'          => $order_id,
            'mid'               => $order_info['mid'],
            'out_refund_no'     => $out_refund_no,
            'create_time'       => getTime(),
            'update_time'       => getTime(),
        ];

        $this->order_model->startTrans();
        $is_commit = true;

        if($this->order_model->where(['order_sn' => $order_info['order_sn']])->save(['update_time' => getTime(), 'status' => OrderModel::STATUS_WAIT, 'out_refund_no' => $out_refund_no]) == false) {
            $is_commit = false;
        }

        if($this->refund_model->add($data) == false) {
            $is_commit = false;
        }

        /*if($this->system_msg_model->addOne($order_info['mid'], '您的退款申请已受理，请耐心等待审核') == false) {
            $is_commit = false;
        }*/
        if($is_commit) {
            $this->order_model->commit();
            exit($this->returnApiSuccess());
        } else {
            $this->order_model->rollback();
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '网络错误，请重试'));
        }
    }

    public function sale() {
        $mid = $this->member_info['mid'];
        $order = $this->order_model
            ->alias('a')
            ->where(['mid' => $mid, 'a.status' => ['in', [OrderModel::STATUS_WAIT, OrderModel::STATUS_RETURN]]])
            ->join('left join he_order_product as b on a.id = b.order_id')
            ->join('left join he_pro_option as c on b.option_id = c.option_id')
            ->join('left join he_product as d on b.pro_id = d.pro_id')
            ->field('a.id as order_id,a.status, a.order_price,b.quantity,  b.number,b.cover_photo,b.price, b.pro_id, c.option_name, d.product_name, a.create_time')
            ->order('a.create_time desc')
            ->select();
        foreach ($order as $k => $v) {
            $order[$k]['status_string'] = $this->order_model->getUserStatusString($v['status']);
        }

        $this->assign('list', $order);
        $this->display();
    }

    public function cancel() {
        $order_id = I('post.order_id');
        if($this->order_model->where(['id' => $order_id])->save(['status' => OrderModel::STATUS_CANCEL])) {
            exit($this->returnApiSuccess());
        } else {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR));
        }
    }

    public function del() {
        $order_id = I('post.order_id');
        if($this->order_model->where(['id' => $order_id])->save(['shows' => OrderModel::SHOW_OFF])) {
            exit($this->returnApiSuccess());
        } else {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR));
        }
    }
}